<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#00f7ff">
    <title>股票训练 - Tech Edition</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600;700&family=Rajdhani:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div class="container">

        <div class="training-container">
            <div class="image-container">
                <div id="loadingSpinner" class="image-loading"></div>
                <img id="currentImage" src="" alt="股票图片" style="display: none;">
                <div id="timer" class="timer">5</div>
                <div id="result" class="result-container" style="display: none;">
                    <div class="result-text"></div>
                    <div class="correct-answer"></div>
                </div>
            </div>

            <div class="controls">
                <button id="upButton" class="btn btn-up" onclick="makeGuess('UP')" disabled>
                    看涨
                </button>
                <button id="downButton" class="btn btn-down" onclick="makeGuess('DOWN')" disabled>
                    看跌
                </button>
            </div>

            <div class="nav-buttons">
                <button id="prevBtn" class="btn btn-secondary" onclick="loadPreviousImage()" disabled>
                    上一题
                </button>
                <button id="nextBtn" class="btn btn-primary" onclick="loadNextImage()">
                    下一题
                </button>
            </div>

            <div class="stats-container">
                <div>正确: <span id="correctCount">0</span></div>
                <div>错误: <span id="incorrectCount">0</span></div>
                <div>正确率: <span id="accuracy">0.0%</span></div>
            </div>
        </div>

        <div id="status" class="status"></div>
    </div>

    <script>
        // 全局变量
        let currentImageInfo = null;
        let timerInterval = null;
        let isFirstImage = true;
        let isLoading = false;
        
        const stats = {
            correct: 0,
            incorrect: 0
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadNewImage();
            loadStatsFromLocalStorage();
        });

        // 保存统计信息到本地存储
        function saveStatsToLocalStorage() {
            localStorage.setItem('trainingStats', JSON.stringify(stats));
        }

        // 从本地存储加载统计信息
        function loadStatsFromLocalStorage() {
            const savedStats = localStorage.getItem('trainingStats');
            if (savedStats) {
                Object.assign(stats, JSON.parse(savedStats));
                updateStats();
            }
        }

        // 更新统计信息显示
        function updateStats() {
            document.getElementById('correctCount').textContent = stats.correct;
            document.getElementById('incorrectCount').textContent = stats.incorrect;
            
            const total = stats.correct + stats.incorrect;
            const accuracy = total > 0 ? ((stats.correct / total) * 100).toFixed(1) : '0.0';
            document.getElementById('accuracy').textContent = accuracy + '%';
            
            saveStatsToLocalStorage();
        }

        // 加载图片
        function loadImage(url) {
            return new Promise((resolve, reject) => {
                const img = document.getElementById('currentImage');
                const spinner = document.getElementById('loadingSpinner');
                
                spinner.style.display = 'block';
                img.style.display = 'none';
                
                img.onload = () => {
                    spinner.style.display = 'none';
                    img.style.display = 'block';
                    resolve();
                };
                
                img.onerror = () => {
                    spinner.style.display = 'none';
                    reject(new Error('图片加载失败'));
                };
                
                img.src = url;
            });
        }

        // 加载新图片
        async function loadNewImage() {
            if (isLoading) return;
            isLoading = true;
            
            try {
                clearInterval(timerInterval);
                disableButtons(true);
                document.getElementById('prevBtn').disabled = isFirstImage;
                
                const response = await fetch('/api/random-image');
                if (!response.ok) throw new Error('Failed to load image');
                
                const data = await response.json();
                currentImageInfo = data;
                
                await loadImage('/api/images/' + data.path);
                
                hideResult();
                disableButtons(false);
                startTimer();
                isFirstImage = false;
            } catch (error) {
                console.error('Error:', error);
                showStatus('加载图片失败，请刷新页面重试', false);
            } finally {
                isLoading = false;
            }
        }

        // 加载上一张图片
        async function loadPreviousImage() {
            if (isLoading) return;
            isLoading = true;
            
            try {
                clearInterval(timerInterval);
                disableButtons(true);
                
                const response = await fetch('/api/previous-image');
                if (!response.ok) throw new Error('No previous image');
                
                const data = await response.json();
                currentImageInfo = data;
                
                await loadImage('/api/images/' + data.path);
                
                hideResult();
                disableButtons(false);
                startTimer();
            } catch (error) {
                showStatus('没有更多历史记录', false);
                document.getElementById('prevBtn').disabled = true;
            } finally {
                isLoading = false;
            }
        }

        // 加载下一张图片
        async function loadNextImage() {
            if (isLoading) return;
            await loadNewImage();
            document.getElementById('prevBtn').disabled = false;
        }

        // 开始计时器
        function startTimer(duration = 5) {
            clearInterval(timerInterval);
            
            const timerDisplay = document.getElementById('timer');
            let timeLeft = duration;
            
            timerDisplay.textContent = timeLeft;
            timerDisplay.style.display = 'block';

            timerInterval = setInterval(() => {
                timeLeft--;
                if (timeLeft < 0) {
                    clearInterval(timerInterval);
                    handleTimeout();
                    return;
                }
                timerDisplay.textContent = timeLeft;
            }, 1000);
        }

        // 处理超时
        function handleTimeout() {
            disableButtons(true);
            showResult('时间到！', '正确答案是: ' + 
                (currentImageInfo.type === 'UP' ? '看涨' : '看跌'));
            stats.incorrect++;
            updateStats();

            // 2.3秒后启用按钮（等待动画完成）
            setTimeout(() => {
                disableButtons(false);
            }, 2300);
        }

        // 处理猜测
        function makeGuess(guess) {
            if (isLoading) return;
            
            clearInterval(timerInterval);
            disableButtons(true);

            const isCorrect = guess === currentImageInfo.type;
            if (isCorrect) {
                stats.correct++;
                showResult('正确！', '', true);
            } else {
                stats.incorrect++;
                showResult('错误！', '正确答案是: ' + 
                    (currentImageInfo.type === 'UP' ? '看涨' : '看跌'), false);
            }
            
            updateStats();
            document.getElementById('prevBtn').disabled = false;

            // 2.3秒后启用按钮（等待动画完成）
            setTimeout(() => {
                disableButtons(false);
            }, 2300);
        }

        // 显示结果
        function showResult(text, answer, isSuccess = false) {
            const result = document.getElementById('result');
            result.querySelector('.result-text').textContent = text;
            result.querySelector('.correct-answer').textContent = answer;
            result.className = 'result-container ' + (isSuccess ? 'success' : 'error');
            result.style.display = 'block';
            result.style.animation = 'fadeIn 0.3s ease-out';

            // 2秒后自动隐藏
            setTimeout(() => {
                result.style.animation = 'fadeOut 0.3s ease-out';
                setTimeout(() => {
                    result.style.display = 'none';
                }, 300);
            }, 2000);
        }

        // 隐藏结果
        function hideResult() {
            document.getElementById('result').style.display = 'none';
        }

        // 禁用/启用按钮
        function disableButtons(disabled) {
            document.getElementById('upButton').disabled = disabled;
            document.getElementById('downButton').disabled = disabled;
        }

        // 显示状态消息
        function showStatus(message, isSuccess, duration = 3000) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = 'status ' + (isSuccess ? 'success' : 'error');
            status.style.display = 'block';
            
            if (duration > 0) {
                setTimeout(() => {
                    status.style.display = 'none';
                }, duration);
            }
        }

        // 页面离开前清理
        window.addEventListener('beforeunload', () => {
            clearInterval(timerInterval);
        });
    </script>
</body>
</html> 